package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecParam;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SpecParamMapper;
import com.leyou.item.service.SpecParamService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class SpecParamServiceImpl extends ServiceImpl<SpecParamMapper, SpecParam> implements SpecParamService {
    @Autowired
    SpuDetailService spuDetailService;
    @Autowired
    SpuService spuService;

    @Override
    public List<SpecParamDTO> querySpecParamByCategoryIdAndGroupId(Long cid, Long gid, Boolean search) {
        //健壮性判断
        if (cid == null && gid ==null){
            //条件不能都为空
            throw new LyException("查询条件不能为空",400);
        }
        List<SpecParam> specParamList = query()
        .eq(cid!=null,"category_id",cid)
        .eq(gid!=null,"group_id",gid)
        .eq(search!=null,"searching",search)
        .list();
        return SpecParamDTO.convertEntityList(specParamList);
    }

    @Override
    public List<SpecParamDTO> querySpecValues(Long spuId, Boolean searching) {
        //1.准备规格参数值
        SpuDetail spuDetail = spuDetailService.getById(spuId);
            //1.0 获取规格参数值 ,记住这是 该spud下多个spec规格参数值 ,这里是手机
            //手机的规格参数值是18个，根据规格参数的id，注入对应的规格参数值。
        String specification = spuDetail.getSpecification();
            //1.1规格参数值(必须为json类型),转为map
        Map<Long, Object> specValues = JsonUtils.toMap(specification, Long.class, Object.class);
        //2.准备分类id
        Spu spu = spuService.getById(spuId);
            //2.0获取分类id
        Long categoryId = spu.getCid3();
        //3.准备Spec_param数据
        List<SpecParam> specParamList = query().eq("category_id", categoryId).eq(searching!=null,"searching",searching).list();
            //3.1转换 po ---> dto
        List<SpecParamDTO> specParamDTOList = SpecParamDTO.convertEntityList(specParamList);
        //4.遍历注入数据 根据规格参数id注入对应的规格参数值。
        //比如 是规格参数1 ，注入的值 华为 ； 规格参数3 年份，对应的规格参数 是 2016
        for (SpecParamDTO specParamDTO : specParamDTOList) {
            specParamDTO.setValue(specValues.get(specParamDTO.getId()));
        }
        return specParamDTOList;
    }

}
